/*
 * @lc app=leetcode.cn id=687 lang=typescript
 *
 * [687] 最长同值路径
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function longestUnivaluePath(root: TreeNode | null): number {
  let ans = 0;

  const dfs = (root: TreeNode | null): number => {
    if (!root) return 0;
    // 递归左右子树
    let l = dfs(root.left);
    let r = dfs(root.right);
    // 计算左右同值节点路径长度
    let lcount = 0;
    let rcount = 0;
    // 通过判断左右子树节点值是否跟当前节点相等，计算路径长度
    if (root.left && root.left.val === root.val) {
      lcount = l + 1;
    }
    if (root.right && root.right.val === root.val) {
      rcount = r + 1;
    }
    // 更新答案
    ans = Math.max(ans, lcount + rcount);
    // 返回左右子树最长的路径长度
    return Math.max(lcount, rcount);
  };

  dfs(root);
  return ans;
}
// @lc code=end
